﻿@inherits BaseComponent

@if (sysFiles != null && sysFiles.Count > 0)
{
    foreach (var item in sysFiles)
    {
        <div class="kui-app-upload">
            <img src="@item.FileUrl.OriginalUrl" />
        </div>
    }
}
@if (files != null && files.Count > 0)
{
    for (int i = 0; i < files.Count; i++)
    {
        <div class="kui-app-upload"><img id="@ImgId(i)" /></div>
    }
}
<div class="kui-app-upload">
    <Icon Type="camera" Theme="outline" />
    <InputFile id="" @ref="inputFile" OnChange="OnInputFileChanged" />
</div>

@code {
    private IFileService fileService;
    private InputFile inputFile;
    private Dictionary<string, ElementReference> imgElems = [];
    private List<SysFile> sysFiles;
    private List<IBrowserFile> files = [];
    private string ImgId(int i) => $"img-{Id}-{i}";

    [Parameter] public string Value { get; set; }
    [Parameter] public Action<List<IBrowserFile>> OnFilesChanged { get; set; }

    public bool HasFile => sysFiles != null && sysFiles.Count > 0 || files.Count > 0;

    protected override async Task OnInitAsync()
    {
        await base.OnInitAsync();
        fileService = await Factory.CreateAsync<IFileService>(Context);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
            sysFiles = await fileService.GetFilesAsync(Value);
    }

    private async void OnInputFileChanged(InputFileChangeEventArgs e)
    {
        if (e.FileCount == 0)
            return;

        files.Add(e.File);
        OnFilesChanged?.Invoke(files);
        StateChanged();
        await JS.PreviewImageByIdAsync(inputFile.Element, ImgId(files.Count - 1));
    }
}